import axios from 'axios';
import { MessageBox } from 'element-ui';
import { getQueryByName } from '@/utils/utils';
import { Config } from '@/config';

const caches = {
  isFetching: false,
  userInfo: null,
  resolve: null,
  promise: null,
  isNotValid: false,
  addTask: async (task) => {
    await caches.promise;
    return task(caches.userInfo);
  },
  init() {
    if (caches.promise) {
      return;
    }
    caches.promise = new Promise(resolve => {
      caches.resolve = resolve;
    });
  },
};

const request = axios.create({
  baseURL: '/bladesystem',
  timeout: 600000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
});

request.defaults.validateStatus = (status) => {
  // 由于登录失效时，接口返回的status为401，此时不会走response的拦截器函数，所以这里需要把401状态处理成正常请求。。。
  return [401, 200].includes(status);
}

const fetchUserInfo = async () => {
  const code = getQueryByName(location.href, 'code');
  if (!code) {
    MessageBox.alert('非法访问，该页面必须登录才能使用，点击确定跳转登录页面', '提示', {
      type: 'warning',
      showClose: false,
    }).then(() => {
      window.location.replace(Config.loginUrl);
    });
    return {};
  }
  const res = await request({
    url: '/api/blade-system/authentication/parsing',
    method: 'get',
    params: {
      code,
    },
  });
  const data = res.data;
  if (data.code === 200) {
    const userInfo = data.data || {};

    caches.userInfo = userInfo;
    sessionStorage.setItem('user-info', JSON.stringify({
      ...userInfo,
      code,
    }));
    return {
      ...userInfo,
      code,
    };
  }
  return {};
}


request.interceptors.response.use(async (response) => {
  const data = response.data;
  if (data.code === 401 && !caches.isNotValid) {
    sessionStorage.removeItem('user-info');
    caches.userInfo = null;
    caches.isNotValid = true;
    MessageBox.alert('登录失效，需要重新登录，点击确定跳转登录页面', '提示', {
      showClose: false,
      type: 'warning',
    }).then(() => {
      // window.location.replace('http://119.23.128.21:9030/#/');
      window.location.replace('http://172.22.12.11:22203/#/');
    });
    caches.init();
    return caches.promise;
  }
  if (caches.isNotValid) {
    return caches.promise;
  }
  return response;
});

request.interceptors.request.use(async (config) => {
  if (config.url.includes('authentication/parsing')) {
    return config;
  }
  if (caches.isFetching) {
    return caches.addTask((data) => {
      return {
        ...config,
        headers: {
          'Blade-Auth': data.token,
        },
      }
    });
  }
  const userInfo = JSON.parse(sessionStorage.getItem('user-info') || '{}');
  if (!caches.userInfo && !userInfo.token) {
    caches.isFetching = true;
    caches.init();
    const userData = await fetchUserInfo();
    caches.isNotValid = false;
    caches.isFetching = false;
    caches.resolve(userData);
    return {
      ...config,
      headers: {
        'Blade-Auth': userData.token,
      },
    };
  }

  const data = caches.userInfo || userInfo;
  if (data.token) {
    return {
      ...config,
      headers: {
        'Blade-Auth': data.token,
      },
    };
  }

  return config;
});

export const saveArea = (data) => {
  return request({
    url: '/api/blade-system/area/submit',
    method: 'post',
    data,
  });
};

export const getAreaList = (size, current) => {
  return request({
    url: '/api/blade-system/area/list',
    method: 'get',
    params: {
      current,
      size,
    },
  });
};

export const getAreaInfo = (id) => {
  return request({
    url: '/api/blade-system/area/item',
    method: 'get',
    params: { id },
  });
}

export const deleteArea = (id) => {
  return request({
    url: '/api/blade-system/area/remove',
    method: 'post',
    data: {
      id
    },
  });
}

export const clearAll = () => {
  return request({
    url: '/api/blade-system/area/removeAll',
    method: 'get'
  });
}

//获取设备数据
export const getDevicePlayUrl = (params) => {
  return request({
    url: '/api/blade-system/equipmentManagement/equipmentIdPlay',
    method: 'get',
    params: params,
  });
}

//获取开放位置
export const getKeyLocations = (params) => {
  return request({
    url: '/api/blade-system/keyLocations/getListAll',
    method: 'get',
    params: params,
  });
}
//获取热力图点位 // 获取专题图数据
export const getSituationalHeatMap = () => {
  return request({
    url: '/api/blade-system/situationalHeatMap/list',
    method: 'GET',
  });
}
//获取系统模型
export const getListEnterprise = () => {
  return request({
    url: '/api/blade-system/modelManagement/listEnterprise',
    method: 'GET',
  });
}

//获取开放位置
export const selectDeviceByLongitudeAndLatitude = (params) => {
  return request({
    url: '/api/blade-system/device/selectDeviceByLongitudeAndLatitude',
    method: 'POST',
    data: params,
  });
}

// 获取设备分类
export const getDeviceTypes = () => {
  return request({
    url: '/api/blade-system/dict/dictionary-tree',
    method: 'GET',
    params: { code: 'device_type' }
  })
}

//获取设备列表
export const getDeviceData = () => {
  return request({
    url: '/api/blade-system/device/list/public',
    method: 'GET',
  });
}


// 获取标点位置列表
export const getMarkPointItem = (id) => {
  return request({
    url: '/api/blade-system/spacePlotting/item',
    method: 'get',
    params: { id }
  })
}
export const getMarkList = () => {
  return request({
    url: '/api/blade-system/spacePlotting/list',
  })
}

// 新增/编辑 标点
export const saveMark = (data) => {
  return request({
    url: '/api/blade-system/spacePlotting/submit',
    method: 'post',
    data: data
  })

}

// 删除表点
export const delMark = (id) => {
  return request({
    url: '/api/blade-system/spacePlotting/remove',
    method: 'get',
    params: {
      id
    },
  })
}

// 获取模型数据列表
export const getModelList = () => {
  return request({
    url: '/api/blade-system/modelManagement/list'
  })
}
